<template>
  <div>
    <!-- 表头分页查询条件， shadow="never" 指定 card 卡片组件没有阴影 -->
    <el-card shadow="never" class="mb-5">
      <!-- flex 布局，内容垂直居中 -->
      <div class="flex items-center">
        <el-text>文章标题</el-text>
        <div class="ml-3 w-52 mr-5">
          <el-input v-model="searchArticleTitle" placeholder="请输入（模糊查询）"/>
        </div>

        <el-text>创建日期</el-text>
        <div class="ml-3 w-30 mr-5">
          <!-- 日期选择组件（区间选择） -->
          <el-date-picker v-model="pickDate" type="daterange" range-separator="至" start-placeholder="开始时间"
                          end-placeholder="结束时间" size="default" :shortcuts="shortcuts" @change="datepickerChange"/>
        </div>

        <el-button type="primary" class="ml-3" :icon="Search" @click="getTableData">查询</el-button>
        <el-button class="ml-3" :icon="RefreshRight" @click="reset">重置</el-button>
      </div>
    </el-card>

    <el-card shadow="never">
      <!-- 写文章按钮 -->
      <div class="mb-5">
        <el-button type="primary" @click="isArticlePublishEditorShow = true">
          <el-icon class="mr-1">
            <EditPen/>
          </el-icon>
          写文章
        </el-button>
      </div>

      <!-- 分页列表 -->
      <el-table :data="tableData" border stripe style="width: 100%" v-loading="tableLoading">
        <el-table-column prop="id" label="编号" width="80"/>
        <el-table-column prop="title" label="标题" width="380"/>
        <el-table-column prop="cover" label="封面" width="180">
          <template #default="scope">
            <el-image style="width: 80px; height: 50px" :src="scope.row.cover"/>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="发布时间" width="180"/>
        <el-table-column prop="isTop" label="置顶" width="60">
          <template #default="scope">
            <el-switch
                v-model="scope.row.isTop"
                class="mr-3"
                style="--el-switch-on-color: #139cce; --el-switch-off-color: #a8d5e3"
                @click="setTop(scope.row.id, scope.row.isTop)"
            />
          </template>

        </el-table-column>
        <el-table-column label="操作" width="360">
          <template #default="scope">
            <el-button size="small" @click="gotoArticleDetail(scope.$index, scope.row)">
              <el-icon class="mr-1">
                <View/>
              </el-icon>
              预览
            </el-button>
            <el-button size="small" @click="showArticleUpdateEditor(scope.$index, scope.row)">
              <el-icon class="mr-1">
                <Edit/>
              </el-icon>
              编辑
            </el-button>
            <el-button type="danger" size="small" @click="delArticle(scope.$index, scope.row)">
              <el-icon class="mr-1">
                <Delete/>
              </el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="mt-10 flex justify-center">
        <el-pagination v-model:current-page="current" v-model:page-size="size" :page-sizes="[10, 20, 50]"
                       :small="false" :background="true" layout="total, sizes, prev, pager, next, jumper"
                       :total="total" @size-change="handleSizeChange" @current-change="getTableData"/>
      </div>

    </el-card>

    <!-- 写博客 -->
    <el-dialog v-model="isArticlePublishEditorShow" :fullscreen="true" :show-close="false" class="p-3">
      <template #header="{ close, titleId, titleClass }">
        <div class="my-header flex justify-center items-center">
          <h4 :id="titleId" :class="titleClass" class="font-bold left">发布文章</h4>
          <!-- 头部 -->
          <div class="ml-auto flex">
            <el-button round type="default" @click="close">
              <el-icon class="mr-2">
                <Delete/>
              </el-icon>
              取消
            </el-button>
            <el-button round type="primary" @click="publishArticle">
              <el-icon class="mr-2">
                <Promotion/>
              </el-icon>
              发布
            </el-button>
          </div>
        </div>
        <!-- 标题 -->
        <el-form class="mt-2.5" ref="publishArticleFormRef" :model="form" label-width="160px" :rules="rules"
                 label-position="top">
          <el-form-item label="标题" prop="title">
            <el-input v-model="form.title" clearable/>
          </el-form-item>
          <el-form-item label="内容" prop="content">
            <!-- Markdown 编辑器 -->
            <MdEditor
                v-model="form.content"
                @onUploadImg="onUploadImg"
                editorId="publishArticleEditor">
            </MdEditor>
          </el-form-item>
          <el-form-item label="封面" prop="cover">
            <el-upload class="cover-uploader" action="#"
                       :on-change="handleCoverChange" :auto-upload="false"
                       :show-file-list="false">
              <img v-if="form.cover" :src="form.cover" class="cover w-32"/>
              <el-icon v-else class="cover-uploader-icon">
                <Plus/>
              </el-icon>
            </el-upload>
          </el-form-item>
          <el-form-item label="摘要" prop="summary">
            <el-input type="textarea" rows="4" v-model="form.summary" clearable/>
          </el-form-item>
          <el-form-item label="分类" prop="categoryId" style="width: 600px">
            <el-select v-model="form.categoryId" clearable placeholder="---请选择---" size="large">
              <el-option v-for="item in categoryData" :key="item.value" :label="item.label" :value="item.value"/>
            </el-select>
          </el-form-item>
          <el-form-item label="标签" prop="tags" class="w-48" style="width: 600px">
            <el-select v-model="form.tags" multiple filterable remote reserve-keyword placeholder="请输入文章标签"
                       remote-show-suffix allow-create default-first-option :remote-method="remoteMethod"
                       :loading="tagSelectLoading"
                       size="large">
              <el-option v-for="item in tags" :key="item.value" :label="item.label" :value="item.value"/>
            </el-select>
          </el-form-item>
        </el-form>
      </template>
    </el-dialog>

    <el-dialog v-model="outerVisible" title="Outer Dialog" width="800">
      <span>This is the outer Dialog</span>
      <el-dialog
          v-model="innerVisible"
          width="500"
          title="Inner Dialog"
          append-to-body
      >
        <span>This is the inner Dialog</span>
      </el-dialog>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="outerVisible = false">Cancel</el-button>
          <el-button type="primary" @click="innerVisible = true">
            Open the inner Dialog
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 文章编辑功能开发 -->
    <!-- 编辑博客 -->
    <el-dialog v-model="isArticleUpdateEditorShow" :fullscreen="true" :show-close="false" class="p-3">
      <template #header="{ close, titleId, titleClass }">
        <div class="my-header flex justify-center items-center">
          <h4 :id="titleId" :class="titleClass" class="font-bold left">编辑文章</h4>
          <!-- 头部 -->
          <div class="ml-auto flex">
            <el-button round type="default" @click="close">
              <el-icon class="mr-2">
                <Delete/>
              </el-icon>
              取消
            </el-button>
            <el-button round type="primary" @click="updateArticle">
              <el-icon class="mr-2">
                <Promotion/>
              </el-icon>
              发布
            </el-button>
          </div>
        </div>
        <!-- 标题 -->
        <el-form class="mt-2.5" ref="updateArticleFormRef" :model="updateArticleForm" label-width="160px" :rules="rules"
                 label-position="top">
          <el-form-item label="标题" prop="title">
            <el-input v-model="updateArticleForm.title" clearable/>
          </el-form-item>
          <el-form-item label="内容" prop="content">
            <!-- Markdown 编辑器 -->
            <MdEditor @onUploadImg="onUploadImg" v-model="updateArticleForm.content" editorId="publishArticleEditor"/>
          </el-form-item>
          <el-form-item label="封面" prop="cover">
            <el-upload class="cover-uploader" action="#"
                       :on-change="handleUpdateCoverChange" :auto-upload="false"
                       :show-file-list="false">
              <img v-if="updateArticleForm.cover" :src="updateArticleForm.cover" class="cover w-32"/>
              <el-icon v-else class="cover-uploader-icon">
                <Plus/>
              </el-icon>
            </el-upload>
          </el-form-item>
          <el-form-item label="摘要" prop="summary">
            <el-input type="textarea" rows="4" v-model="updateArticleForm.summary" clearable/>
          </el-form-item>
          <el-form-item label="分类" prop="categoryId" style="width: 600px">
            <el-select v-model="updateArticleForm.categoryId" clearable placeholder="---请选择---" size="large">
              <el-option v-for="item in categoryData" :key="item.value" :label="item.label" :value="item.value"/>
            </el-select>
          </el-form-item>
          <el-form-item label="标签" prop="tags" class="w-48" style="width: 600px">
            <el-select v-model="updateArticleForm.tags" multiple filterable remote reserve-keyword
                       placeholder="请输入文章标签"
                       remote-show-suffix allow-create default-first-option :remote-method="remoteMethod"
                       :loading="tagSelectLoading"
                       size="large">
              <el-option v-for="item in tags" :key="item.value" :label="item.label" :value="item.value"/>
            </el-select>
          </el-form-item>
        </el-form>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {onMounted, reactive, ref} from 'vue'
import {RefreshRight, Search} from '@element-plus/icons-vue'
import moment from 'moment'
import {articleDel, articlequeryByPage, articleDetail, articleAdd, articleUpdate, unsetArticleTop, setArticleTop} from "@/api/admin/article.js"
import {showMessage, showModel, showNotification} from "@/composables/util.js";
import {MdEditor} from 'md-editor-v3'
import 'md-editor-v3/lib/style.css'
import {uploadFile} from '@/api/admin/file'
import {categoryQueryList} from "@/api/admin/category.js";
import {tagQueryList, getTagSelectList} from "@/api/admin/tag.js"
import {useRouter} from "vue-router";

const router = useRouter()
// 模糊搜索的文章标题
const searchArticleTitle = ref('')
// 日期
const pickDate = ref('')

// 查询条件：开始结束时间
const startDate = reactive({})
const endDate = reactive({})

// 监听日期组件改变事件，并将开始结束时间设置到变量中
const datepickerChange = (e) => {
  startDate.value = moment(e[0]).format('YYYY-MM-DD')
  endDate.value = moment(e[1]).format('YYYY-MM-DD')
}

const shortcuts = [
  {
    text: '最近一周',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      return [start, end]
    },
  },
  {
    text: '最近一个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      return [start, end]
    },
  },
  {
    text: '最近三个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
      return [start, end]
    },
  },
]

// 重置
const reset = () => {
  pickDate.value = ''
  startDate.value = null
  endDate.value = null
  searchArticleTitle.value = ''
}

// 表格加载 Loading
const tableLoading = ref(false)
// 表格数据
const tableData = ref([])
// 当前页码，给了一个默认值 1
const current = ref(1)
// 总数据量，给了个默认值 0
const total = ref(0)
// 每页显示的数据量，给了个默认值 10
const size = ref(10)
// 是否显示文章发布对话框
const isArticlePublishEditorShow = ref(false)
// 发布文章表单引用
const publishArticleFormRef = ref(null)
// 分页数据
const categoryData = ref([])
// 文章标签
const tags = ref([])
// 表单校验规则
const rules = {
  title: [
    {required: true, message: '请输入文章标题', trigger: 'blur'},
    {min: 1, max: 40, message: '文章标题要求大于1个字符，小于40个字符', trigger: 'blur'},
  ],
  content: [{required: true}],
  cover: [{required: true}],
  categoryId: [{required: true, message: '请选择文章分类', trigger: 'blur'}],
  tags: [{required: true, message: '请选择文章标签', trigger: 'blur'}],
}
// 表单对象
const form = reactive({
  id: null,
  title: '',
  content: '请输入内容',
  cover: '',
  categoryId: null,
  tags: [],
  summary: ""
})

const isArticleUpdateEditorShow = ref(false)
// 编辑文章表单引用
const updateArticleFormRef = ref(null)

// 修改文章表单对象
const updateArticleForm = reactive({
  id: null,
  title: '',
  content: '请输入内容...',
  cover: '',
  categoryId: null,
  tags: [],
  summary: ""
})

const outerVisible = ref(false)

// 标签 select Loading 状态，默认不显示
const tagSelectLoading = ref(false)

onMounted(() => {
  getTableData()
  fetchCategoryData()
  getTagSelectList().then(res => {
    tags.value = res.data
  })
})

// 获取分页数据
function getTableData() {

  tableLoading.value = true
  const data = {
    "current": current.value,
    "size": size.value,
    "searchTitle": searchArticleTitle.value,
    "endDate": endDate.value,
    "startDate": startDate.value
  }
  articlequeryByPage(data).then(resp => {
    if (resp.success) {
      tableData.value = resp.data
      current.value = resp.current
      size.value = resp.size
      total.value = resp.total
    } else {
      showNotification("文章", resp.message, "warning")
    }
  }).finally(() => {
    tableLoading.value = false
  })
}

// 得到分类数据
function fetchCategoryData() {
  categoryQueryList().then(resp => {
    if (resp.success) {
      categoryData.value = resp.data
    }
  })
}

// 每页展示数量变更事件
const handleSizeChange = (chooseSize) => {
  size.value = chooseSize
  getTableData()
}

// 删除文章
const delArticle = (index, row) => {
  showModel(`确认删除${row.title}这篇文章？`, "文章删除").then(() => {
    articleDel(row.id).then(resp => {
      if (resp.success) {
        showNotification("删除文章", `删除${row.title}文章成功`)
        tableLoading.value = true
        getTableData()
      } else {
        showNotification("删除文章", resp.message, "warning")
      }
    }).finally(() => {
      tableLoading.value = false
    })
  })
}

// 上传文章封面图片
const handleCoverChange = (file) => {
  // 表单对象
  let formData = new FormData()
  // 添加 file 字段，并将文件传入
  formData.append('file', file.raw)
  uploadFile(formData).then((e) => {
    // 响参失败，提示错误消息
    if (e.success === false) {
      let message = e.message
      showMessage(message, 'error')
      return
    }

    // 成功则设置表单对象中的封面链接，并提示上传成功
    form.cover = e.data.url
    showMessage('上传成功')
  })
}

// 根据用户输入的标签名称，远程模糊查询
const remoteMethod = (query) => {
  console.log('远程搜索：' + tags.value)
  // 如果用户的查询关键词不为空
  if (query) {
    // 显示 loading
    tagSelectLoading.value = true
    // 调用标签模糊查询接口
    tagQueryList({"tagName": query}).then((e) => {
      if (e.success) {
        // 设置到 tags 变量中
        tags.value = e.data
      }
    }).finally(() => tagSelectLoading.value = false) // 隐藏 loading
  }
}

// 发布文章
const publishArticle = () => {
  // 校验表单
  publishArticleFormRef.value.validate((valid) => {
    if (!valid) {
      return false
    }

    articleAdd(form).then((res) => {
      if (res.success === false) {
        // 获取服务端返回的错误消息
        let message = res.message
        // 提示错误消息
        showNotification("发布文章", message, 'error')
        return
      }

      showNotification("发布文章", "发布成功")
      // 隐藏发布文章对话框
      isArticlePublishEditorShow.value = false
      // 将 form 表单字段置空
      form.title = ''
      form.content = ''
      form.cover = ''
      form.summary = ''
      form.categoryId = null
      form.tags = []
      // 重新请求分页接口，渲染列表数据
      getTableData()
    })
  })
}

// 编辑文章：上传文章封面图片
const handleUpdateCoverChange = (file) => {
  // 表单对象
  let formData = new FormData()
  // 添加 file 字段，并将文件传入
  formData.append('file', file.raw)
  uploadFile(formData).then((e) => {
    // 响参失败，提示错误消息
    if (e.success === false) {
      let message = e.message
      showMessage(message, 'error')
      return
    }

    // 成功则设置表单对象中的封面链接，并提示上传成功
    updateArticleForm.cover = e.data.url
    showMessage('上传成功')
  })
}
// 编辑文章按钮点击事件
const showArticleUpdateEditor = (index, row) => {
  // 显示编辑文章对话框
  isArticleUpdateEditorShow.value = true
  // 拿到文章 ID
  let articleId = row.id
  articleDetail(articleId).then((res) => {
    if (res.success) {
      // 设置表单数据
      updateArticleForm.id = res.data.id
      updateArticleForm.title = res.data.title
      updateArticleForm.cover = res.data.cover
      updateArticleForm.content = res.data.content
      updateArticleForm.categoryId = res.data.categoryId
      updateArticleForm.tags = res.data.tagIds
      updateArticleForm.summary = res.data.summary
    }
  })
}

const updateArticle = () => {
  // 校验表单
  updateArticleFormRef.value.validate((valid) => {
    if (!valid) {
      return false
    }

    articleUpdate(updateArticleForm).then((res) => {
      if (res.success === false) {
        // 获取服务端返回的错误消息
        let message = res.message
        // 提示错误消息
        showNotification("修改文章", message, 'error')
        return
      }

      showNotification("修改文章", "修改成功")
      // 隐藏发布文章对话框
      isArticleUpdateEditorShow.value = false
      // 将 form 表单字段置空
      updateArticleForm.title = ''
      updateArticleForm.content = ''
      updateArticleForm.cover = ''
      updateArticleForm.summary = ''
      updateArticleForm.categoryId = null
      updateArticleForm.tags = []
      // 重新请求分页接口，渲染列表数据
      getTableData()
    })
  })
}
// 编辑器图片上传
const onUploadImg = async (files, callback) => {
  const res = await Promise.all(
      files.map((file) => {
        return new Promise((rev, rej) => {
          console.log('==> 编辑器开始上传文件...')
          let formData = new FormData()
          formData.append("file", file);
          uploadFile(formData).then((res) => {
            // 调用 callback 函数，回显上传图片
            callback([res.data.url]);
          })
        });
      })
  );
}

const gotoArticleDetail = (index, row) => {
  let articleId = row.id
  router.push('/article/detail/' + articleId)
}

// 设置文章为置顶状态
const setTop = (id, isTop) => {
  /**
   * 根据 isTop 进行判断，判断是否置顶
   */
  if (isTop) {
    setArticleTop(id).then(resp => {
      if (resp.success) {
        showMessage("文章设置置顶成功！")
      } else {
        showNotification("文章置顶", resp.message,"warning")
      }
    })
  } else {
    unsetArticleTop(id).then(resp => {
      if (resp.success) {
        showMessage("文章取消置顶成功！")
      } else {
        showNotification("取消置顶", resp.message,"warning")
      }
    })
  }
}

</script>

<style>
.cover-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.cover-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.cover-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}

.md-editor-footer {
  height: 40px;
}
</style>

<style scoped>
.cover-uploader .cover {
  width: 178px;
  height: 178px;
  display: block;
}
</style>